﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using KL.UFrame.Core.Unity;
using KL.UFrame.Data.Business;

namespace KL.UFrame.Api.Controllers
{
    public class ReportController : Controller
    {
        private IReportBusiness _business = UnityBootstrapper.Current.GetService<IReportBusiness>();
        private ITokenManager _tokenManager = UnityBootstrapper.Current.GetService<ITokenManager>();

        private static DataTable _emptyTable;

        public static DataTable EmptyTable
        {
            get
            {
                if (_emptyTable == null)
                {
                    _emptyTable = new DataTable();
                    _emptyTable.Columns.Add(new DataColumn("提示"));
                    var row = _emptyTable.NewRow();
                    row[0] = "您没有下载权限或者下载令牌已失效";
                    _emptyTable.Rows.Add(row);
                }
                return _emptyTable;
            }
        }

        public async Task Export(int reportId, DateTime start, DateTime end,string token)
        {
            DataTable table;
            if (!_tokenManager.ValidateToken(token))
            {
                table = EmptyTable;
            }
            else
            {
                table =await _business.ExportAsync(reportId, start, end);
            }
            ExportDataTableToExcel(table);
        }

        private void ExportDataTableToExcel(DataTable table)
        {
            string url = Request.Url.Scheme + "://" + Request.Url.Host;
            string fileName = string.IsNullOrEmpty(table.TableName) ? "业务报表" : table.TableName;
            int tRowCount = table.Rows.Count;
            int tColumnCount = table.Columns.Count;

            Response.Expires = 0;
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "utf-8";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "application/vnd.ms-<a href='" + url + "' target='_blank' class='keylink'>excel</a>";
            //设定档名可为中文_#1
            //通知浏览器下载文件而不是打开
            if (Request.UserAgent.ToLower().Contains("firefox"))
            {
                Response.AddHeader("Content-Disposition", "attachment;filename=\""
                    + fileName + ".xls\"");
            }
            else
            {
                Response.AddHeader("Content-Disposition", "attachment;filename=\""
                    + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls\"");
            }
            //引用这三个xmlns
            Response.Write("<html xmlns:o='urn:schemas-microsoft-com:office:office'");
            Response.Write("xmlns:x='urn:schemas-microsoft-com:office:<a href='" + url + "' target='_blank' class='keylink'>excel</a>'");
            Response.Write("xmlns='http://www.w3.org/TR/REC-html40'>");

            Response.Write("<meta http-equiv='Content-Type content=text/html;charset=utf-8'>");

            //在head中加入xml定义
            Response.Write("\n <head>");
            Response.Write("\n <xml>");
            Response.Write("\n <x:ExcelWorkbook>");
            Response.Write("\n <x:ExcelWorksheets>");
            Response.Write("\n <x:ExcelWorksheet>");
            //设定此Worksheet名称_#2
            Response.Write("\n <x:Name>报表</x:Name>");

            //以下针对此工作表进行属性设定
            Response.Write("\n <x:WorksheetOptions>");
            Response.Write("\n <x:FrozenNoSplit/>");

            //设定冻结行号_#3
            Response.Write("\n <x:SplitHorizontal>1</x:SplitHorizontal>");

            //设定起始行号(TopRowBottomPane)_#4
            Response.Write("\n <x:TopRowBottomPane>2</x:TopRowBottomPane>");
            Response.Write("\n <x:ActivePane>2</x:ActivePane>");
            Response.Write("\n </x:WorksheetOptions>");
            Response.Write("\n </xml>");
            Response.Write("\n </head>");

            Response.Write("\n <body>");
            Response.Write("<Table borderColor=black border=1>");
            Response.Write("\n <TR>");

            //塞入head
            for (int i = 0; i < tColumnCount; i++)
            {
                //设定head的背景色_#5
                Response.Write("\n <TD  bgcolor = #fff8dc>");
                Response.Write(table.Columns[i].ColumnName);
                Response.Write("\n </TD>");
            }

            Response.Write("\n </TR>");

            //塞入每一笔资料
            for (int j = 0; j < tRowCount; j++)
            {
                Response.Write("\n <TR>");
                for (int k = 0; k < tColumnCount; k++)
                {
                    if (j % 2 == 0)
                    {
                        //设定单号资料靠左且背景为绿色_#6
                        Response.Write("\n <TD align=\"left\" x:text bgcolor = CCCCCC  style=\"vnd.ms-excel.numberformat:@\">");
                    }
                    else
                    {
                        //设定双号资料靠右_#7
                        Response.Write("\n <TD align=\"right\" x:text style=\"vnd.ms-excel.numberformat:@\">");
                    }

                    Response.Write(table.Rows[j][k].ToString());
                    Response.Write("\n </TD>");
                }
                Response.Write("\n </TR>");
            }

            Response.Write("</Table>");
            Response.Write("</body>");
            Response.Write("</html>");
            Response.End();
        }
    }
}